
clear all
set more off
 
cd /data2/cedsei/firm/

/* Inputs */ 

local in_chi  	"/data2/cedsei/firm/chi_panel_20230608.dta"
// From A1_definepop
local in_indpop     "/data2/cedsei/firm/not_ind_pop.dta"

/* Outputs */

local out_ana   "/data2/cedsei/firm/ana_panel_20230608.dta"

********************************************************************************
local extract = 1
if `extract'==1 { // Extract month from firm panel
	clear 
	use lopnr_peorgnr lopnr list_dat_ym using `in_indpop'
	duplicates drop
	gen year  = year(dofm(list_dat_ym))
	gen month = month(dofm(list_dat_ym))
	keep lopnr_peorgnr year month 
	bys lopnr_peorgnr year month: gen all = _N
	egen mtem = max(all), by(lopnr_peorgnr year)
	keep if mtem==all 
	bys lopnr_peorgnr year: keep if _n==1 
	keep lopnr_peorgnr year month
	rename month monthnot
	isid lopnr_peorgnr year 
	save monthnot, replace
}

clear 
use "`in_chi'" 
gen temp = mi(s) 
egen mtem = max(temp), by(lopnr_peorgnr)
drop if mtem==1 
drop temp mtem 

merge 1:1 lopnr_peorgnr year using firm_temp    , keep(3) nogen
merge 1:1 lopnr_peorgnr year using firm_temp_ser, keep(3) nogen

// After the merge some firms now do never notify. THis is because the _merge==1
// are thrown away. 
gen temp = chi>0
egen mtem = max(temp), by(lopnr_peorgnr)
keep if mtem==1
drop mtem temp 

gen temp = abs(sales_ser-sales_fek)/sales_ser<.1
egen similar = mean(temp), by(lopnr_peorgnr)
sum similar, d
count
keep if similar>.9
count 
drop temp similar

merge 1:1 lopnr_peorgnr year using monthnot
drop if _merge==2
drop _merge
replace monthnot = 0 if mi(monthnot)

destring bransch_sni2007, replace
destring bransch_sni2002, replace
egen temp = mode(bransch_sni2007), by(lopnr_peorgnr)
replace bransch_sni2007 = temp 
drop if mi(bransch_sni2007)
gen sni = floor(bransch_sni2007/10000)
drop temp 

order lopnr_peorgnr year chi s monthnot n_not
save "`out_ana'", replace 
